package com.example.a2032;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.RemoteException;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCaller;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceListener;
import com.android.internal.telephony.ITelephony;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.ContactUtils;
import com.example.a2032.Utils.DateUtils;
import com.example.a2032.Utils.GeoFenceUtils;
import com.example.a2032.Utils.LocationUtils;
import com.example.a2032.Utils.MoniDataUtils;
import com.example.a2032.Utils.SerialPortUtil;
import com.example.a2032.Utils.SharedPreferenceUtils;
import com.example.a2032.Utils.SignalInfoUtils;
import com.example.a2032.Utils.Utils;
import com.example.a2032.Utils.WebSocketUtils;
import com.example.a2032.Utils.WifiConnectUtils;
import com.example.a2032.activity.BaseActivity;
import com.example.a2032.activity.GeoFenceShowActivity;
import com.example.a2032.activity.GoalTipsActivity;
import com.example.a2032.activity.SmsShowActivity;
import com.example.a2032.adapter.ViewPagerVerticalAdapter;
import com.example.a2032.entity.Contact;
import com.example.a2032.fragment.HomePageFragment;
import com.example.a2032.fragment.SleepHistoryFragment;
import com.example.a2032.fragment.TopFragment;
import com.example.a2032.entity.RealTimeStepData;
import com.example.a2032.entity.SleepData;
import com.example.a2032.net.NetWorkUtil;
import com.example.a2032.net.jstylenet.NetSendUtils;
import com.example.a2032.view.BatteryView;
import com.google.android.material.internal.ContextUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android_serialport_api.SerialPort;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity implements HomePageFragment.OnPageChangeListener {

    @BindView(R.id.ViewPager)
    ViewPager2 viewPager;
    @BindView(R.id.BatteryView)
    BatteryView mBatteryView;

    @BindView(R.id.rl_statusBar)
    RelativeLayout rlStatusBar;
    MyReceiver myReceiver;
    @BindView(R.id.battery)
    ImageView battery;
    @BindView(R.id.iv_rssi)
    ImageView ivRssi;
    @BindView(R.id.iv_wifi)
    ImageView ivWifi;
    private int GPS_REQUEST_CODE = 988;
    private ViewPagerVerticalAdapter viewPagerVerticalAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        String userName = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.watchId);
//        if(TextUtils.isEmpty(userName)){
//            startActivity(BindTipsActivity.class);
//            finish();
//            return;
//        }
        registerReceiver();
        init();
    }

    private static final String TAG = "MainActivity";

    void init() {
      //  ContactUtils.addContact(this,"18926438136","记住");
        Log.i(TAG, "init: ");
        //enableLocation();
        subscribe(this);
        // getSimSignal();
        List<Fragment> list = new ArrayList<>();
        list.add(TopFragment.newInstance());
        list.add(HomePageFragment.newInstance());
        list.add(SleepHistoryFragment.newInstance());
        viewPagerVerticalAdapter = new ViewPagerVerticalAdapter(this, list);
        viewPager.setAdapter(viewPagerVerticalAdapter);
        viewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        viewPager.setCurrentItem(1);
    }

    void setDeviceTime() {
        SerialPortUtil.getInstance().restartSerialPort();
        sendData(BleSdk.setDeviceTime());
        viewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendData(BleSdk.enableRealTimeStep(true, true));
            }
        }, 100);
    }

    void getSimSignal(boolean start) {
        telephonyManager.listen(new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                int dbm = SignalInfoUtils.getSimdBm(telephonyManager);
                int level = SignalInfoUtils.getLevel(dbm);
                int simState = telephonyManager.getSimState();
                //   Log.i(TAG, "onSignalStrengthsChanged: "+level);
                if (simState == TelephonyManager.SIM_STATE_READY) {
                    ivRssi.setImageLevel(level);
                } else {
                    ivRssi.setImageLevel(0);
                }

            }
        }, start ? PhoneStateListener.LISTEN_SIGNAL_STRENGTHS : 0);

    }

    @Override
    public void setUserInputEnabled(boolean enable) {
        viewPager.setUserInputEnabled(enable);
    }

    TelephonyManager telephonyManager;

    private void registerReceiver() {
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        myReceiver = new MyReceiver();
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        mIntentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        mIntentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
        mIntentFilter.addAction(Intent.ACTION_SHUTDOWN);
        mIntentFilter.addAction("com.android.custom.KEY_F2_LONGPRESS");
        mIntentFilter.addAction(GeoFenceUtils.GEOFENCE_BROADCAST_ACTION);
        mIntentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
        mIntentFilter.addAction("android.intent.action.SIM_STATE_CHANGED");
        mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        registerReceiver(myReceiver, mIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null)
            unregisterReceiver(myReceiver);
//        SerialPortUtil.getInstance().closeSerialPort();
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Intent.ACTION_SHUTDOWN:
                    Log.i(TAG, "onReceive: shutDown");
                    break;
                case Intent.ACTION_BOOT_COMPLETED:
                    Log.i(TAG, "onReceive: ACTION_BOOT_COMPLETED");
                   // sendData(BleSdk.sendLowBatteryStatus(1, false));
                    ivWifi.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setDeviceTime();
                        }
                    },1500);

                    break;
                case WifiManager.RSSI_CHANGED_ACTION:
                    WifiConnectUtils wifiConnectUtils = new WifiConnectUtils(MainActivity.this);
                    int wifiLevel = wifiConnectUtils.GetWifiSignal();
                    Log.i(TAG, "onReceive: wifiLevel " + wifiLevel);
                    ivWifi.setImageLevel(wifiLevel);
                    break;
                case "android.provider.Telephony.SMS_RECEIVED":
                    Log.i(TAG, "onReceive: sms");
                    Object[] pdus = (Object[]) intent.getExtras().get("pdus");
                    for (Object pdu : pdus) {
                        SmsMessage smsMessage = SmsMessage
                                .createFromPdu((byte[]) pdu);
                        String sender = smsMessage.getOriginatingAddress();
                        String info = smsMessage.getDisplayMessageBody();
                        Log.i(TAG, "onReceive: " + sender + " " + info);
//                        Intent smsIntent = new Intent(MainActivity.this, SmsShowActivity.class);
//                        smsIntent.putExtra(SmsShowActivity.KEY_SmsInfo, info);
//                        smsIntent.putExtra(SmsShowActivity.KEY_SmsSender, sender);
//                        startActivity(smsIntent);
                    }
                    Log.i(TAG, "onReceive: ");
                    break;
                case GeoFenceUtils.GEOFENCE_BROADCAST_ACTION:
                    Bundle bundle = intent.getExtras();
                    int geoFenceStatus = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                    String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
                    String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
                    GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                    int getStatus=fence.getStatus();
                    startActivity(GeoFenceShowActivity.class,GeoFenceShowActivity.key_Type,getStatus);
                    WebSocketUtils.getInstance().sendMsg(NetSendUtils.snWarn(fence));
                    Log.i(TAG, "onReceive: " + geoFenceStatus + " " + fenceId+" "+customId);
                    break;
                case "android.intent.action.SIM_STATE_CHANGED":
                    int simState = telephonyManager.getSimState();
                    Log.i(TAG, "onReceive: SIM_STATE_CHANGED " + simState);
                    switch (simState) {
                        case TelephonyManager.SIM_STATE_READY:
                            ivRssi.setImageLevel(1);
                            getSimSignal(true);
                            WebSocketUtils.getInstance().sendMsg("");
                            break;
                        case TelephonyManager.SIM_STATE_UNKNOWN:
                        case TelephonyManager.SIM_STATE_ABSENT:
                        case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                        case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                        case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                        default:
                            getSimSignal(false);
                            ivRssi.setImageLevel(0);
                            break;
                    }
                    break;
//                case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
//                    String res = intent.getStringExtra("reason");
//                    Log.i(TAG, "onReceive: " + res);
//                    break;
                case Intent.ACTION_BATTERY_CHANGED:
                    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
                    TopFragment topFragment = (TopFragment) viewPagerVerticalAdapter.getFragment(0);
                    topFragment.updateBatteryValue(level);
                    LocationUtils.getInstance().setBatteryLevel(level);


                    mBatteryView.setBatteryLevel(level, status == BatteryManager.BATTERY_STATUS_CHARGING);
                    break;
                case TelephonyManager.ACTION_PHONE_STATE_CHANGED:
                    int state = telephonyManager.getCallState();
                    String incomingNumber = intent.getStringExtra(
                            TelephonyManager.EXTRA_INCOMING_NUMBER);
                    //answerCall();
                    if (state == TelephonyManager.CALL_STATE_RINGING) {
                        boolean isMoniPhone = MoniDataUtils.getInstance().isMoniPhone(incomingNumber);
                        Log.i(TAG, "onReceive: " + isMoniPhone + " " + incomingNumber);
                        //实时监听(需要系统签名权限)
                        Utils.setProperty("persist.sys.answer_auto_code", isMoniPhone ? "true" : "false");
                    } else {
                        MoniDataUtils.getInstance().removePhone(incomingNumber);
                    }
                    break;
                case "com.android.custom.KEY_F2_LONGPRESS":

                    toSosContact();
                    break;
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (null != parcelableExtra) {
                        NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                        NetworkInfo.State wifiState = networkInfo.getState();
                        ivWifi.setVisibility(wifiState == NetworkInfo.State.CONNECTED ? View.VISIBLE : View.INVISIBLE);
                        if (wifiState == NetworkInfo.State.CONNECTED) {
                            Log.i(TAG, "onReceive: wifi connect");
                        }
                        break;
                    }
                case Intent.ACTION_SCREEN_OFF:
//                    sendData(BleSdk.disableSerialPort());
//                   SerialPortUtil.getInstance().setOpenSerialPort(false);
                    break;
                case Intent.ACTION_SCREEN_ON:
                    Log.i(TAG, "onReceive: ACTION_SCREEN_ON");
                    SerialPortUtil.getInstance().restartSerialPort();
                    WebSocketUtils.getInstance().sendMsg("");
                    toGetSleepData();
                    break;
            }
        }

    }

    long lastSycSleepTime;
    long periodSleepTime = 3600000;

    private void toGetSleepData() {

        Observable.timer(1000, TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long aLong) {
                Log.i(TAG, "onNext: getSleepData");
                if (WebSocketUtils.getInstance().isMeasuring()) {

                } else {
                    if (lastSycSleepTime != 0 && System.currentTimeMillis() - lastSycSleepTime < periodSleepTime)
                        return;
                    sendData(BleSdk.getSleepData());
                    lastSycSleepTime = System.currentTimeMillis();
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    //sos

    /**
     * sos优先级最高，有其他来电的时候先把其他来电挂断（直接挂断再拨打会出现错误？等待1秒再拨打）
     */
    private void toSosContact() {
        LocationUtils.getInstance().startSosLocation();
        int state = telephonyManager.getCallState();
        if (state != TelephonyManager.CALL_STATE_IDLE) {
            endCall();
            Utils.startMeasureTimer(1, TimeUnit.SECONDS, new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Object o) {
                    callSosContact();
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

        } else {
            callSosContact();
        }


    }
    int indexContact=0;
    void callSosContact() {
        List<Contact>list=ContactUtils.getAllContact(this);
        if(list.size()==0){
            Toast.makeText(this, R.string.noContact,Toast.LENGTH_SHORT).show();
            return;
        }
        if(indexContact>=list.size())indexContact=0;
        String call=list.get(indexContact).getPhoneNumber();
        Utils.setProperty("persist.sys.sos_call", "true");
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:"+call);
        intent.putExtra("isSos", true);
        intent.setData(data);
        startActivity(intent);
        indexContact++;
    }

    private void endCall() {
        Method method = null;
        try {
            method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
            ITelephony telephony = ITelephony.Stub.asInterface(binder);
            try {
                telephony.endCall();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    public boolean isLocServiceEnable() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    void enableLocation() {
        if (!isLocServiceEnable()) {
//            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//            startActivityForResult(intent,GPS_REQUEST_CODE);
            //需要系统权限
            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
        } else {
            GeoFenceUtils geoFenceUtils = new GeoFenceUtils(this, 1);
            geoFenceUtils.setGeoFenceListener(new GeoFenceListener() {
                @Override
                public void onGeoFenceCreateFinished(List<GeoFence> list, int errorCode, String s) {
                    if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {//判断围栏是否创建成功
                        Log.i(TAG, "onGeoFenceCreateFinished: success");
                        //geoFenceList是已经添加的围栏列表，可据此查看创建的围栏
                    } else {
                        Log.i(TAG, "onGeoFenceCreateFinished: failed");
                    }
                }
            });
            geoFenceUtils.createGeoFence(22.33d, 33.22d, 15, "2");
        }
    }

    int lastStep = 0;

    @Override
    public void RealTimeData(RealTimeStepData timeStepData) {
        super.RealTimeData(timeStepData);
        int step = timeStepData.getStep();
        int goalStep = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_StepGoal, 10000);
        if (step >= goalStep) {
            toGoalTips(SharedPreferenceUtils.KEY_StepGoalTips2, 1);
        } else if (step >= goalStep / 2) {
            toGoalTips(SharedPreferenceUtils.KEY_StepGoalTips1, 0);
        }
    }

    void toGoalTips(String key, int type) {
        String tipsDate = SharedPreferenceUtils.getString(key, "");
        String todayDate = DateUtils.getDefaultToday(new Date());
        if (TextUtils.isEmpty(tipsDate) || !tipsDate.equals(todayDate)) {
            startActivity(GoalTipsActivity.class, GoalTipsActivity.Goal_Percent, type);
            SharedPreferenceUtils.setSpString(key, todayDate);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //ContactUtils.deleteAllCallLogs(this);
    }

    @Override
    protected void backToHome() {
        super.backToHome();
        if (viewPager != null)
            viewPager.setCurrentItem(1);
    }

    @Override
    public void SleepData(SleepData sleepData, boolean finish) {
        super.SleepData(sleepData, finish);
        if (finish) {
            sendData(BleSdk.setDeviceTime());
        }
    }
}